package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: Sabrina
 * @Date:2025/06/13/17:07
 * @Description:
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 查询当前登录用户的所有地址信息
     * @return
     */
    @Override
    public List<AddressBook> getAddresses() {
        return addressBookMapper.getAddresses(BaseContext.getCurrentId());
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefaultAddress() {
        return addressBookMapper.getDefaultAddress(BaseContext.getCurrentId());
    }


    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressById(Long id) {
        return addressBookMapper.getAddressById(id);
    }

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void addAddr(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.addAddr(addressBook);
    }

    /**
     * 修改地址
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void delete(Integer id) {
        addressBookMapper.delete(id);
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Transactional
    @Override
    public void updateDefault(AddressBook addressBook) {
        //1.把当前用户的所有地址修改为非默认地址
        Long userId = BaseContext.getCurrentId();
        addressBookMapper.updateIsDefaultByUserId(userId);
        //2.把当前地址改为默认地址
        addressBook.setUserId(userId);
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }
}
